package org.example;

import cn.hutool.core.img.Img;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main(String[] args) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String endpoint = "http://localhost:7042";
        String accessKey = "admin";
        String secretKey = "123456";
        String srcBucketName = "tcboot";
        String dstBucketName = "demo";

        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        // 检查源和目标bucket是否存在
        boolean srcBucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(srcBucketName).build());
        boolean dstBucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(dstBucketName).build());
        if (!srcBucketExists || !dstBucketExists) {
            System.out.println("Source or Destination Bucket does not exist.");
            return;
        }

        // 列出源bucket中的所有对象
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(srcBucketName).build());
        for (Result<Item> result : results) {
            Item item = result.get();
            String objectName = item.objectName();

            if(objectName.endsWith("event/")) {
                // 遍历目录中资源
                Iterable<Result<Item>> listObjects = minioClient.listObjects(ListObjectsArgs.builder().bucket(srcBucketName).prefix(objectName).build());
                for (Result<Item> itemResult : listObjects) {
                    Item subItem = itemResult.get();
                    String objName = subItem.objectName();
                    processAndCompressImage(minioClient, srcBucketName, dstBucketName, objName);
                }
                break;
            }
        }

        System.out.println("Bulk image compression and upload completed successfully.");
    }

    private static void processAndCompressImage(MinioClient client, String srcBucket, String dstBucket, String objectName) throws NoSuchAlgorithmException, InsufficientDataException, InternalException, ErrorResponseException, XmlParserException, IOException, ServerException, InvalidKeyException, InvalidResponseException {
        // 下载图片到本地
        File tempFile = new File(System.getProperty("user.dir") + File.separator + objectName);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        File outputFile = tempFile;

        client.downloadObject(DownloadObjectArgs.builder()
                .bucket(srcBucket)
                .object(objectName)
                .filename(tempFile.getAbsolutePath())
                .build());

        if (objectName.endsWith(".jpg") || objectName.endsWith(".jpeg") || objectName.endsWith(".png")) {
            outputFile = new File(tempFile.getParent(), "compressed-" + tempFile.getName());

            // 压缩图片
            Img.from(tempFile)
                    .setQuality(0.5)//压缩比率
                    .write(outputFile);
        }

        // 上传压缩后的图片到目标bucket
        client.uploadObject(UploadObjectArgs.builder()
                .bucket(dstBucket)
                .object(objectName)
                .filename(outputFile.getAbsolutePath())
                .contentType(getContentTypeByContent(tempFile)) // 假设所有图片都是JPEG格式，根据实际情况调整
                .build());

        // 清理临时文件
        Files.deleteIfExists(tempFile.toPath());
        Files.deleteIfExists(outputFile.toPath());
    }

    private static String getContentTypeByContent(File file) {
        Path path = Paths.get(file.getAbsolutePath());
        try {
            String contentType = Files.probeContentType(path);
            return contentType != null ? contentType : "application/octet-stream";
        } catch (IOException e) {
            throw new RuntimeException("Error getting content type of file", e);
        }
    }
}
